<template>
  <div ref="chart" style="height: 100%;" />
</template>
<script>
import { Chart, registerShape } from '@antv/g2';
import { getTicks } from '@/utils/chartScale.js';
import { numFormat } from '@/utils/filter.js';
export default {
/*
  data:     所要传输的数据
  x:        x轴变量名(有默认值)
  y:        y轴变量名(有默认值)
  s:        系列值
  color:    图表颜色
  text:     tooltip中的文字，数组格式
  sText:    s系列值顺序
*/
  name: 'LineChart2',
  props: {
    data: {
      type: Array,
      reqired: true
    },
    x: {
      type: String,
      default: 'x'
    },
    y: {
      type: String,
      default: 'y'
    },
    s: {
      type: String,
      default: 's'
    },
    color: {
      type: Array,
      required: true
    },
    text: {
      type: Array,
      required: true
    },
    sText: {
      type: Array,
      required: false
    }
  },
  data() {
    return {
      chart: null
    };
  },
  watch: {
    data: {
      handler() {
        this.updataData();
      }
    }
  },
  mounted() {
    this.initChart();
    this.drawChart();
  },
  methods: {
    getTicks,
    initChart() {
      const ref = this.$refs.chart;
      this.chart = new Chart({
        container: ref,
        width: ref.clientWidth,
        height: ref.clientHeight
      });
    },
    // 数据分离
    splitData(points) {
      const data1 = [];
      const data2 = [];
      let innerData = [];
      for (let i = 0; i < this.data.length; i++) {
        const beforeType = this.data[i - 1] ? this.data[i - 1][this.s] : null;
        const type = this.data[i][this.s];
        if (i === 0) {
          innerData.push(points[i]);
        } else {
          if (type === beforeType) {
            innerData.push(points[i]);
            if (i === this.data.length - 1) {
              if (beforeType === '自动') {
                data1.push(innerData);
              } else {
                data2.push(innerData);
              }
            }
          } else {
            innerData.push(points[i]);
            if (beforeType === '自动') {
              data1.push(innerData);
            } else {
              data2.push(innerData);
            }
            innerData = [];
            innerData.push(points[i]);
          }
        }
      }
      return [data1, data2];
    },
    drawChart() {
      const ratio = window.ratio || 1;
      const x = this.x;
      const y = this.y;
      const that = this;
      registerShape('line', 'split-line', {
        draw(cfg, container) {
          const points = cfg.points;
          const pointsArrs = that.splitData(points);
          // 自定义 Shape 需要将图形绘制在自己的 Shape/Group 里，并返回之
          const group = container.addGroup();
          const path1 = [];
          const path2 = [];
          for (let i = 0; i < pointsArrs[0].length; i++) {
            const path = pointsArrs[0][i].map((item, index) => {
              const pre = index === 0 ? 'M' : 'L';
              return [pre, item.x, item.y];
            });
            path1.push(path);
          }
          for (let i = 0; i < pointsArrs[1].length; i++) {
            const path = pointsArrs[1][i].map((item, index) => {
              const pre = index === 0 ? 'M' : 'L';
              return [pre, item.x, item.y];
            });
            path2.push(path);
          }
          path1.forEach(item => {
            group.addShape('path', {
              attrs: {
                path: item,
                stroke: '#00fdff',
                lineWidth: 2 * ratio
              }
            });
          });
          path2.forEach(item => {
            group.addShape('path', {
              attrs: {
                path: item,
                stroke: '#34c8ff',
                lineWidth: 2 * ratio
              }
            });
          });
          return group;
        }
      });
      this.chart.data(this.data);
      this.chart.scale(y, {
        min: 0,
        tickCount: 6,
        tickMethod: this.getTicks
      });
      // 提示框
      this.chart.tooltip({
        shared: true,
        showCrosshairs: true,
        crosshairs: {
          line: {
            style: {
              stroke: '#00FDFF',
              lineDash: [3 * ratio, 3 * ratio],
              lineWidth: 1 * ratio
            }
          }
        },
        customItems: items => {
          items.forEach((item) => {
            item.name = item.data.s;
            if (item.name === '自动') {
              item.color = this.color[0];
            } else {
              item.color = this.color[1];
            }
            item.value = numFormat(Number(item.value));
          });
          return items;
        },
        domStyles: {
          'g2-tooltip-title': {
            fontSize: '.875rem',
            color: '#8D8D8D'
          },
          'g2-tooltip-list-item': {
            fontSize: 0,
            overflow: 'hidden'
          },
          'g2-tooltip-name': {
            fontSize: '.75rem',
            color: '#8D8D8D'
          },
          'g2-tooltip-value': {
            fontSize: '.75rem',
            color: 'rgba(0, 0, 0, 0.6)',
            fontWeight: '780'
          }
        }
      });
      // x轴
      this.chart.axis(x, {
        label: {
          style: {
            fill: '#ADADAD',
            fontSize: 12 * ratio,
            fontFamily: 'Helvetica-regular',
            lineHeight: 14 * ratio
          },
          offset: 5 * ratio
        },
        line: {
          style: {
            stroke: '#FFFFFF',
            strokeOpacity: 0.4,
            lineWidth: 1 * ratio
          }
        },
        tickLine: false
      });
      // y轴
      this.chart.axis(y, {
        label: {
          style: {
            fill: '#ADADAD',
            fontSize: 12 * ratio,
            fontFamily: 'Helvetica-regular'
          },
          formatter: (text) => {
            return numFormat(Number(text));
          },
          offset: 5 * ratio,
          autoHide: false
        },
        line: null,
        grid: null
      });
      this.chart.legend(false);
      this.chart
        .line()
        .position(`${x}*${y}`)
        .shape('split-line')
        .animate({
          appear: {
            delay: 0,
            duration: 2000
          }
        });
      this.chart.render();
    },
    // 更新数据
    updataData() {
      this.chart.changeData(this.data);
    }
  }
};
</script>
